package com.bnz.portal.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class MyCacheConfig {
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        //得到默认的缓存配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //修改key的序列化方式
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //修改值的序列化方式
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
        //得到我们自己的配置
        CacheProperties.Redis redis = cacheProperties.getRedis();
        //设置到期时间
        if(redis.getTimeToLive() != null) {
            config = config.entryTtl(redis.getTimeToLive());
        }
        if(!redis.isUseKeyPrefix()){
            config = config.disableKeyPrefix();
        }
        if(!redis.isCacheNullValues()){
            config = config.disableCachingNullValues();
        }
        if(redis.getKeyPrefix() != null){
            config = config.prefixCacheNameWith(redis.getKeyPrefix());
        }
        //...
        return config;
    }

}
